<template>
  <el-main>
    <!-- 搜索栏 -->
    <el-form :model="searchParm" :inline="true" size="default">
      <el-form-item>
        <el-select
          v-model="searchParm.categoryId"
          class="m-2"
          placeholder="请选择类型"
          size="default"
        >
          <el-option
            v-for="item in categoryList"
            :key="item['value']"
            :label="item['label']"
            :value="item['value']"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="searchParm.roomName"
          placeholder="请输入阅览室名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="searchBtn" icon="Search">搜索</el-button>
        <el-button @click="resetBtn" type="danger" plain icon="Close"
          >重置</el-button
        >
        <el-button icon="Plus" type="primary" @click="addBtn">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :height="tableHeight" :data="tableList" border stripe>
      <el-table-column label="阅览室图片" align="center">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 60px"
            :src="scope.row.image.split(',')[0]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="roomName" label="阅览室名称"></el-table-column>
      <el-table-column prop="categoryName" label="类型"></el-table-column>
      <el-table-column prop="floorName" label="楼层"></el-table-column>
      <el-table-column prop="numX" label="座位行数"></el-table-column>
      <el-table-column prop="numY" label="座位列数"></el-table-column>
      <el-table-column prop="area" label="区域"></el-table-column>
      <el-table-column prop="beginTime" label="开门时间"></el-table-column>
      <el-table-column prop="endTime" label="关门时间"></el-table-column>
      <el-table-column label="座位总数">
        <template #default="scope">
          <span>{{ scope.row.numX * scope.row.numY }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button
            type="primary"
            icon="Edit"
            size="default"
            @click="editBtn(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="Delete"
            size="default"
            @click="deleteBtn(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="sizeChange"
      @current-change="currentChange"
      :current-page.sync="searchParm.currentPage"
      :page-sizes="[10, 20, 40, 80, 100]"
      :page-size="searchParm.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="searchParm.total"
      background
    >
    </el-pagination>
  </el-main>
  <!-- 弹框 -->
  <SysDialog
    :title="dialog.title"
    :width="dialog.width"
    :height="dialog.height"
    :visible="dialog.visible"
    @on-close="onClose"
    @on-confirm="commit"
  >
    <template v-slot:content>
      <el-form
        :model="addModel"
        ref="addRef"
        :rules="rules"
        label-width="100px"
        :inline="false"
        size="normal"
      >
        <el-form-item prop="roomName" label="阅览室名称:">
          <el-input
            v-model="addModel.roomName"
            placeholder="请输入阅览室名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="categoryId" label="阅览室类型:">
          <el-select
            style="width: 100%"
            v-model="addModel.categoryId"
            class="m-2"
            placeholder="请选择类型"
            size="default"
          >
            <el-option
              v-for="item in categoryList"
              :key="item['value']"
              :label="item['label']"
              :value="item['value']"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="floorId" label="阅览室楼层:">
          <el-select
            style="width: 100%"
            v-model="addModel.floorId"
            class="m-2"
            placeholder="请选择楼层"
            size="default"
          >
            <el-option
              v-for="item in floorList"
              :key="item['value']"
              :label="item['label']"
              :value="item['value']"
            />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12" :offset="0">
            <el-form-item prop="numX" label="座位行数:">
              <el-input
                v-model="addModel.numX"
                placeholder="请输入阅览室行数"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item prop="numY" label="座位列数:">
              <el-input
                v-model="addModel.numY"
                placeholder="请输入阅览室列数"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" :offset="0">
            <el-form-item prop="area" label="阅览室区域:">
              <el-input
                v-model="addModel.area"
                placeholder="请输入阅览室区域"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item prop="orderNum" label="序号:">
              <el-input
                v-model="addModel.orderNum"
                placeholder="请输入序号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" :offset="0">
            <el-form-item prop="beginTime" label="开门时间:">
              <el-time-picker
                v-model="addModel.beginTime"
                value-format="HH:mm:ss"
                format="HH:mm:ss"
                splaceholder="请选择开门时间"
              ></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item prop="endTime" label="关门时间:">
              <el-time-picker
                v-model="addModel.endTime"
                value-format="HH:mm:ss"
                format="HH:mm:ss"
                splaceholder="请选择关门时间"
              ></el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="image" label="图片:">
          <UploadImage
            @getImg="getImg"
            ref="uploadRef"
            :fileList="fileList"
            :oldUrl="oldUrl"
          ></UploadImage>
        </el-form-item>
      </el-form>
    </template>
  </SysDialog>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import UploadImage from "@/components/UploadImage.vue";
import { ElMessage, FormInstance, UploadUserFile } from "element-plus";
import { getSelectApi } from "@/api/room_category/index";
import { Room, addApi, getListApi, editApi, deleteApi } from "@/api/room/index";
import { getSelectFloorApi } from "@/api/room_floor/index";
import { NewType } from "@/type/BaseType";
import useInstance from "@/hooks/useInstance";
const { global } = useInstance();
//图片上传ref属性
const uploadRef = ref();
//图片回显的数据
const fileList = ref<Array<UploadUserFile>>([]);
//图片默认的url
const oldUrl = ref<Array<{ url: string }>>([]);
const imgUrl = ref<Array<{ url: string }>>([]);
const addRef = ref<FormInstance>();
//新增表单对象
const addModel = reactive({
  roomId: "",
  roomName: "",
  image: "",
  categoryId: "",
  floorId: "",
  numX: "",
  numY: "",
  area: "",
  orderNum: "",
  beginTime: "",
  endTime: "",
});
const rules = reactive({
  roomName: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请填写阅览室名称",
    },
  ],
  image: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请上传图片",
    },
  ],
  categoryId: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请选择类型",
    },
  ],
  floorId: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请选择层数",
    },
  ],
  numX: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请填写行数",
    },
  ],
  numY: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请填写列数",
    },
  ],
  beginTime: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请选择开门时间",
    },
  ],
  endTime: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请选择关门时间",
    },
  ],
});
//弹框属性
const { dialog, onClose, onShow } = useDialog();
//搜索参数
const searchParm = reactive({
  currentPage: 1,
  pageSize: 10,
  categoryId: "",
  roomName: "",
  total: 0,
});
//标识：0新增 1编辑
const tags = ref();
//新增按钮
const addBtn = () => {
  tags.value = "0";
  imgUrl.value = [];
  oldUrl.value = [];
  fileList.value = [];
  //清空表单
  addRef.value?.resetFields();
  dialog.height = 430;
  dialog.width = 800;
  onShow();
};
//编辑
const editBtn = (row: Room) => {
  tags.value = "1";
  imgUrl.value = [];
  oldUrl.value = [];
  fileList.value = [];
  //清空表单
  addRef.value?.resetFields();
  dialog.height = 430;
  dialog.width = 800;
  onShow();
  //编辑数据回显
  nextTick(() => {
    Object.assign(addModel, row);
    //图片回显
    if (addModel.image) {
      //转换为数组
      let imgs = addModel.image.split(",");
      for (let i = 0; i < imgs.length; i++) {
        let img = { name: "", url: "" };
        img.name = imgs[i];
        img.url = imgs[i];
        fileList.value.push(img);
        oldUrl.value.push({ url: imgs[i] });
      }
    }
  });
};
//删除
const deleteBtn = async (row: Room) => {
  console.log(row);
  const confirm = await global.$myconfirm("确定删除该数据库吗?");
  if (confirm) {
    let res = await deleteApi(row.roomId);
    if (res && res.code == 200) {
      ElMessage.success(res.msg);
      //刷新表格
      getList();
    }
  }
};
//查询类型下拉数据
const categoryList = ref([]);
const getSelect = async () => {
  let res = await getSelectApi();
  if (res && res.code == 200) {
    categoryList.value = res.data;
  }
};
//楼层下拉数据
const floorList = ref([]);
const getSelectFloor = async () => {
  let res = await getSelectFloorApi();
  if (res && res.code == 200) {
    floorList.value = res.data;
  }
};
//图片上传返回
const getImg = (img: NewType) => {
  console.log(img);
  imgUrl.value = oldUrl.value.concat(img.newImgUrl);
  if (img.deleteUrl.length > 0) {
    //删除数据
    let newArr = imgUrl.value.filter(
      (x) => !img.deleteUrl.some((item) => x.url == item.url)
    );
    imgUrl.value = newArr;
  }
  let url = "";
  //图片地址转为逗号分隔的字符串  aa.png,bb.png,
  for (let k = 0; k < imgUrl.value.length; k++) {
    url = url + imgUrl.value[k].url + ",";
  }
  //去掉字符串最后一个逗号
  addModel.image = url.substring(0, url.lastIndexOf(","));
};
//提交表单
const commit = () => {
  console.log(addModel);
  addRef.value?.validate(async (valid) => {
    if (valid) {
      let res = null;
      if (tags.value == "0") {
        res = await addApi(addModel);
      } else {
        res = await editApi(addModel);
      }
      if (res && res.code == 200) {
        ElMessage.success(res.msg);
        //清空图片
        uploadRef.value.clearimg();
        //刷新表格
        getList();
        onClose();
      }
    }
  });
};
//表格数据
const tableList = ref([]);
//获取列表数据
const getList = async () => {
  let res = await getListApi(searchParm);
  if (res && res.code == 200) {
    tableList.value = res.data.records;
    searchParm.total = res.data.total;
  }
};
//页容量改变时触发
const sizeChange = (size: number) => {
  searchParm.pageSize = size;
  getList();
};
//页数改变时触发
const currentChange = (page: number) => {
  searchParm.currentPage = page;
  getList();
};
//搜索
const searchBtn = () => {
  getList();
};
//重置
const resetBtn = () => {
  searchParm.categoryId = "";
  searchParm.currentPage = 1;
  searchParm.roomName = "";
  getList();
};
//表格高度
const tableHeight = ref(0);
onMounted(() => {
  getList();
  getSelect();
  getSelectFloor();
  nextTick(() => {
    tableHeight.value = window.innerHeight - 230;
  });
});
</script>

<style scoped></style>
